//
//  UserMovieLabelVC.m
//  MovieDate
//
//  Created by ann on 16/4/6.
//  Copyright © 2016年 MovieDate. All rights reserved.
//

#import "UserMovieLabelVC.h"
#import "MovieLabelVCTableViewCell.h"

@interface UserMovieLabelVC () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
{
    NSString *pStrType;
    NSMutableArray *pArraySelect;
    ///存请求下来的数据
    NSMutableArray *pArrayData;
}

@property (weak, nonatomic) IBOutlet UITextField *customMyLabelTXF;

@property(nonatomic,strong) NSMutableArray *dataArr;
@property(nonatomic,assign) NSInteger curSelectIndex;
@property(nonatomic,strong) NSString *userCurSelectMovieLabel;
@property(nonatomic,strong) NSString *lastSelectMovieLabel;
@property(nonatomic,strong) NSString *uuid;

@end

@implementation UserMovieLabelVC

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.block != nil)
    {
        if ([self.pNavTitle isEqualToString:@"星座"]) {
           self.block(self.lastSelectMovieLabel,1,self.uuid, [NSArray array]);
        }else if ([self.pNavTitle isEqualToString:@"美食"]) {
           self.block(self.lastSelectMovieLabel,2,self.uuid, pArraySelect);
        }else if ([self.pNavTitle isEqualToString:@"电影"]){
           self.block(self.lastSelectMovieLabel,3,self.uuid, pArraySelect);
        }else if ([self.pNavTitle isEqualToString:@"演员"]){
           self.block(self.lastSelectMovieLabel,4,self.uuid, pArraySelect);
        }else if ([self.pNavTitle isEqualToString:@"导演"]){
           self.block(self.lastSelectMovieLabel,5,self.uuid, pArraySelect);
        }else if ([self.pNavTitle isEqualToString:@"电影类型"]){
           self.block(self.lastSelectMovieLabel,6,self.uuid, pArraySelect);
        }else if ([self.pNavTitle isEqualToString:@"常去影院"]){
           self.block(self.lastSelectMovieLabel,7,self.uuid, pArraySelect);
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    pArraySelect = [NSMutableArray array];
    pArrayData = [NSMutableArray array];
    self.title = self.pNavTitle;
    self.customMyLabelTXF.delegate = self;
    NSDictionary *constellationDic = @{@"constellation":[@[] mutableCopy]};
    NSDictionary *cateDic = @{@"cate":[@[] mutableCopy]};
    NSDictionary *movieDic = @{@"movie":[@[] mutableCopy]};
    NSDictionary * actressDic = @{@"actress":[@[] mutableCopy]};
    NSDictionary * directionDic = @{@"direction":[@[] mutableCopy]};
    NSDictionary * movieTypeDic = @{@"movieType":[@[] mutableCopy]};
    NSDictionary * cinemaDic = @{@"cinema":[@[] mutableCopy]};
    
    [self.dataArr addObject:constellationDic];
    [self.dataArr addObject:cateDic];
    [self.dataArr addObject:movieDic];
    [self.dataArr addObject:actressDic];
    [self.dataArr addObject:directionDic];
    [self.dataArr addObject:movieTypeDic];
    [self.dataArr addObject:cinemaDic];
    //创建视图
    [self initView];
    //获取数据
    [self getData];
}

- (void)initView
{
    if ([self.pNavTitle isEqualToString:@"星座"]) {
        UIView  *view = [[UIView alloc]init];
        self.pTableView.tableHeaderView = view;
        self.pTableView.tableHeaderView.hidden = YES;
        NSLog(@"");
    } else {
        self.pTableView.tableHeaderView.hidden = NO;
    }
    
    //设置导航栏
    [self selAddLeftBackButton];
    
    [self selAddRightButton:@"完成" selector:@selector(cilckFinishBNT)];
    //设置当前cell 默认cell不存在
    self.curSelectIndex = 10000000000;
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentTableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1;
    tableViewGesture.cancelsTouchesInView = NO;
    [self.pTableView addGestureRecognizer:tableViewGesture];
    self.pTableView.delegate = self;
    self.pTableView.dataSource = self;
}

- (void)returnText:(returnBlock)block {
    self.block = block;
}

- (void)selAddLeftBackButton
{
    UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    [btnBack setImage:[UIImage imageNamed:@"back2"] forState:UIControlStateNormal];
    [btnBack setTitle:@"   " forState:UIControlStateNormal];
    [btnBack.titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
    [btnBack setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnBack setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [btnBack addTarget:self action:@selector(selPopOrDismissViewController) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem = leftBarItem;
}

- (void)selAddRightButton:(NSString *)strTitle  selector:(SEL)theSelector
{
    UIButton *btnRight = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    if (strTitle.length > 0) {
        NSDictionary *attrs = @{NSFontAttributeName : btnRight.titleLabel.font};
        CGSize size = [strTitle boundingRectWithSize:CGSizeMake(1000, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
        if (size.width < 50) {
            [btnRight setFrame:CGRectMake(0, 0, 50, 30)];
        } else if (size.width > 100) {
            [btnRight setFrame:CGRectMake(0, 0, 100, 30)];
        } else {
            [btnRight setFrame:CGRectMake(0, 0, size.width, 30)];
        }
        
        [btnRight setTitle:strTitle forState:UIControlStateNormal];
        [btnRight.titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
        [btnRight setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btnRight setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    }
//    if (strImageName.length > 0) {
//        @autoreleasepool {
//            UIImage *imgBtn = [UIImage imageNamed:strImageName];
//            [btnRight setImage:imgBtn forState:UIControlStateNormal];
//            [btnRight.imageView setContentMode:UIViewContentModeScaleAspectFit];
//            btnRight.imageEdgeInsets = UIEdgeInsetsMake(0, btnRight.frame.size.width - btnRight.frame.size.height, 0, 0);
//        }
//    }
    [btnRight addTarget:self action:theSelector forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
    self.navigationItem.rightBarButtonItem = rightBarItem;
}


- (void)cilckFinishBNT
{
    if (self.customMyLabelTXF.text!= NULL&&self.userCurSelectMovieLabel==NULL&&![self.customMyLabelTXF.text isEqualToString:@""]) {
        self.lastSelectMovieLabel = self.customMyLabelTXF.text;
        
        [self updateMovieLabelWithName:self.customMyLabelTXF.text];
        
    }else if (self.customMyLabelTXF.text==NULL&&self.userCurSelectMovieLabel!=NULL ){
        [self updateMovieLabelWithName:self.userCurSelectMovieLabel];
        self.lastSelectMovieLabel = self.userCurSelectMovieLabel;
    }else if([self.customMyLabelTXF.text isEqualToString:@""]&&self.userCurSelectMovieLabel!=NULL ){
        self.lastSelectMovieLabel = self.userCurSelectMovieLabel;
          [self updateMovieLabelWithName:self.userCurSelectMovieLabel];
    }else{
    
        [SVProgressHUD showErrorWithStatus:@"亲~ 没有发现您设置的影签"];
    }
}

- (void)updateMovieLabelWithName:(NSString *)name
{
    if ([self.pNavTitle isEqualToString:@"星座"]) {
        
        [TDNetwork insertLabel:insertMovieLabel_interface name:name type:1 complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            if (succeed) {
                
                self.uuid =  [NSString stringWithFormat:@"%@",[dictionary valueForKey:@"res"]];
                
                   [self selPopOrDismissViewController];
            }
        }];
    }else if ([self.pNavTitle isEqualToString:@"美食"]) {
        [TDNetwork insertLabel:insertMovieLabel_interface name:name type:2 complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            if (succeed) {
                     self.uuid =  [NSString stringWithFormat:@"%@",[dictionary valueForKey:@"res"]];
                [self selPopOrDismissViewController];
            }
        }];
    }else if ([self.pNavTitle isEqualToString:@"电影"]){
        [TDNetwork insertLabel:insertMovieLabel_interface name:name type:3 complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            if (succeed) {
                     self.uuid =  [NSString stringWithFormat:@"%@",[dictionary valueForKey:@"res"]];
                [self selPopOrDismissViewController];
            }
        }];
    }else if ([self.pNavTitle isEqualToString:@"演员"]){
        [TDNetwork insertLabel:insertMovieLabel_interface name:name type:4 complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            if (succeed) {
               self.uuid =  [NSString stringWithFormat:@"%@",[dictionary valueForKey:@"res"]];
                [self selPopOrDismissViewController];
            }
        }];
    }else if ([self.pNavTitle isEqualToString:@"导演"]){
        [TDNetwork insertLabel:insertMovieLabel_interface name:name type:5 complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            if (succeed) {
                    self.uuid =  [NSString stringWithFormat:@"%@",[dictionary valueForKey:@"res"]];
                [self selPopOrDismissViewController];
            }
        }];
    }else if ([self.pNavTitle isEqualToString:@"电影类型"]){
        [TDNetwork insertLabel:insertMovieLabel_interface name:name type:6 complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            if (succeed) {
                      self.uuid =  [NSString stringWithFormat:@"%@",[dictionary valueForKey:@"res"]];
                [self selPopOrDismissViewController];
            }
        }];
    }else if ([self.pNavTitle isEqualToString:@"常去影院"]){
        [TDNetwork insertLabel:insertMovieLabel_interface name:name type:7 complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
            if (succeed) {
                      self.uuid =  [NSString stringWithFormat:@"%@",[dictionary valueForKey:@"res"]];
                [self selPopOrDismissViewController];
            }
        }];
    }
}

//获取数据
- (void)getData
{
    if ([self.pNavTitle isEqualToString:@"星座"]) {
        pStrType = @"1";
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:0];
        NSMutableArray *arr = [dic valueForKey:@"constellation"];
        [self requestDataWithType:1 withsaveArr:arr];
    }else if ([self.pNavTitle isEqualToString:@"美食"]) {
        pStrType = @"2";
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:1];
        NSMutableArray *arr = [dic valueForKey:@"cate"];
        [self requestDataWithType: 2 withsaveArr:arr];
    }else if ([self.pNavTitle isEqualToString:@"电影"]){
        pStrType = @"3";
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:2];
        NSMutableArray *arr = [dic valueForKey:@"movie"];
        [self requestDataWithType:3 withsaveArr:arr];
    }else if ([self.pNavTitle isEqualToString:@"演员"]){
        pStrType = @"4";
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:3];
        NSMutableArray *arr = [dic valueForKey:@"actress"];
        [self requestDataWithType:4 withsaveArr:arr];
    }else if ([self.pNavTitle isEqualToString:@"导演"]){
        pStrType = @"5";
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:4];
        NSMutableArray *arr = [dic valueForKey:@"direction"];
        [self requestDataWithType:5 withsaveArr:arr];
    }else if ([self.pNavTitle isEqualToString:@"电影类型"]){
        pStrType = @"6";
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:5];
        NSMutableArray *arr = [dic valueForKey:@"movieType"];
        [self requestDataWithType:6 withsaveArr:arr];
    }else if ([self.pNavTitle isEqualToString:@"常去影院"]){
        pStrType = @"7";
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:6];
        NSMutableArray *arr = [dic valueForKey:@"cinema"];
        [self requestDataWithType:7 withsaveArr:arr];
    }
}

- (void)requestDataWithType:(NSInteger)type withsaveArr:(NSMutableArray *)saveArr
{
    [TDNetwork requestMovieLabelList:movieLabelList_interface page:1 pageSize:20 type:type complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
        if (succeed) {
            NSDictionary *dic = [dictionary valueForKey:@"res"];
            NSArray *arr = [dic valueForKey:@"labelList"];
           
            for (NSDictionary *labelDic in arr) {
                [saveArr addObject:[labelDic valueForKey:@"name"]];
                [pArrayData addObject:labelDic];
            }
            [self.pTableView reloadData];
        }
    }];
}

//回收键盘
- (void)commentTableViewTouchInSide {
    [_customMyLabelTXF resignFirstResponder];
}


#pragma mark - UITableViewDataSource,UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self.pNavTitle isEqualToString:@"星座"]) {
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:0];
        NSMutableArray *arr = [dic valueForKey:@"constellation"];
        return arr.count;
    }else if ([self.pNavTitle isEqualToString:@"美食"]) {
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:1];
        NSMutableArray *arr = [dic valueForKey:@"cate"];
        return arr.count;
    }else if ([self.pNavTitle isEqualToString:@"电影"]){
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:2];
        NSMutableArray *arr = [dic valueForKey:@"movie"];
        return arr.count;
    }else if ([self.pNavTitle isEqualToString:@"演员"]){
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:3];
        NSMutableArray *arr = [dic valueForKey:@"actress"];
        return arr.count;
    }else if ([self.pNavTitle isEqualToString:@"导演"]){
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:4];
        NSMutableArray *arr = [dic valueForKey:@"direction"];
        return arr.count;
    }else if ([self.pNavTitle isEqualToString:@"电影类型"]){
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:5];
        NSMutableArray *arr = [dic valueForKey:@"movieType"];
        return arr.count;
    }else if ([self.pNavTitle isEqualToString:@"常去影院"]){
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:6];
        NSMutableArray *arr = [dic valueForKey:@"cinema"];
        return arr.count;
        
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = @"idMovieLabelVC";
    MovieLabelVCTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[MovieLabelVCTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    
    UILabel *title = [cell.contentView viewWithTag:1000];
    UIImageView *selectImageView = [cell.contentView viewWithTag:1001];
    selectImageView.hidden = YES;
    if ([self.pNavTitle isEqualToString:@"星座"]) {
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:0];
        NSMutableArray *arr = [dic valueForKey:@"constellation"];
        title.text = [arr objectAtIndex:indexPath.row];
    }else if ([self.pNavTitle isEqualToString:@"美食"]) {
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:1];
        NSMutableArray *arr = [dic valueForKey:@"cate"];
        title.text = [arr objectAtIndex:indexPath.row];
    }else if ([self.pNavTitle isEqualToString:@"电影"]){
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:2];
        NSMutableArray *arr = [dic valueForKey:@"movie"];
        title.text = [arr objectAtIndex:indexPath.row];
    }else if ([self.pNavTitle isEqualToString:@"演员"]){
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:3];
        NSMutableArray *arr = [dic valueForKey:@"actress"];
        title.text = [arr objectAtIndex:indexPath.row];
    }else if ([self.pNavTitle isEqualToString:@"导演"]){
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:4];
        NSMutableArray *arr = [dic valueForKey:@"direction"];
        title.text = [arr objectAtIndex:indexPath.row];
    }else if ([self.pNavTitle isEqualToString:@"电影类型"]){
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:5];
        NSMutableArray *arr = [dic valueForKey:@"movieType"];
        title.text = [arr objectAtIndex:indexPath.row];
    }else if ([self.pNavTitle isEqualToString:@"常去影院"]){
        NSMutableDictionary *dic = [self.dataArr objectAtIndex:6];
        NSMutableArray *arr = [dic valueForKey:@"cinema"];
        title.text = [arr objectAtIndex:indexPath.row];
    }
    
    if (![pStrType isEqualToString:@"1"]) {
        BOOL isSelect = NO;
        for (NSDictionary *item in pArraySelect) {
            if ([[item objectForKey:@"name"] isEqualToString:title.text]) {
                isSelect = YES;
            }
        }
        cell.isSelected = isSelect;
    } else {
        cell.isSelected = (_curSelectIndex == indexPath.row);
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MovieLabelVCTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    self.userCurSelectMovieLabel = cell.titleLB.text;
    self.customMyLabelTXF.text = nil;
    _curSelectIndex = indexPath.row;
    
    if (![pStrType isEqualToString:@"1"]) {
        @try {
            NSDictionary *dictExist = nil;
            for (NSDictionary *item in pArraySelect) {
                if ([[item objectForKey:@"name"] isEqualToString:cell.titleLB.text]) {
                    dictExist = item;
                    break;
                }
            }
            
            if (dictExist) {
                [pArraySelect removeObject:dictExist];
            } else {
                if (pArraySelect.count >= 6) {
                    [SVProgressHUD showErrorWithStatus:@"最多可选择6个"];
                    return;
                }

                NSMutableDictionary *dic = [pArrayData objectAtIndex:indexPath.row];
                [pArraySelect addObject:dic];
            }
        } @catch (NSException *exception) {
        } @finally {
        }
    }
    
    [self.pTableView reloadData];
}


#pragma mark textFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    //点击输入框的时候将所有cell 去掉非选择状态
    _curSelectIndex = 1000000000000;
    self.userCurSelectMovieLabel = nil;
    [self.pTableView reloadData];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
